package com.blb.service.admin.impl;

import com.blb.dao.admin.AdminDao;
import com.blb.dao.admin.impl.AdminDaoImpl;
import com.blb.pojo.Admin;
import com.blb.pojo.Page;
import com.blb.service.admin.IAdminService;
import com.blb.utils.ApplicationContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminServiceImpl implements IAdminService {

    @Autowired
    private AdminDao adminDao ;

    @Override
    public Admin login(Admin admin) throws Exception {
        Admin admin1 = adminDao.selectByName(admin.getName());
        if(admin1==null){
            throw new Exception("账号不存在");
        }
        if(!admin1.getPwd().equals(admin.getPwd())){
            throw new Exception("密码错误");
        }
        return admin1;
    }

    @Override
    public Page<Admin> page(int page, int size, String name) throws Exception {
        List<Admin> list = adminDao.selectPageByName(page, size, name);
        int count = adminDao.count(name);
        return new Page<Admin>(page, size, list, count);
    }

    @Override
    public void add(Admin admin) throws Exception {
        Admin admin1 = adminDao.selectByName(admin.getName());
        if(admin1!=null){
            throw new Exception("管理员账户已存在，请改正");
        }
        adminDao.insert(admin);
    }

    @Override
    public void deleteById(int id) throws Exception {
        if(id==1){
            throw new Exception("超级管理员不能被删除");
        }
        adminDao.deleteById(id);
    }

    @Override
    public void batchDelete(String[] ids) throws Exception {
        for (String id : ids) {
            if (id.equals("1")){
                throw new Exception("超级管理员不能被删除");
            }
        }
        adminDao.batchDelete(ids);
    }

    @Override
    public Admin getById(int id) throws Exception {
        return adminDao.selectById(id);
    }

    @Override
    public void update(Admin admin) throws Exception {
        Admin admin1 = adminDao.selectByName(admin.getName());
        if (admin1 != null && admin1.getId()!=admin.getId()){
            throw new Exception("管理员名称已经存在，请换一个再试");
        }
        adminDao.update(admin);
    }
}
